<template>
  <div class="searchbox-container">
    <div class="searchbox-fields" :class="{'searchbox-fields-collapsed': isCollapsed }">
      <template v-for="field in visibleFields" :key="field.prop">
        <div class="searchbox-field" v-if="field.isHidden != true">
          <label v-if="field.showLabel !== false" class="searchbox-label">{{ field.name }}:</label>

          <!-- Input 类型 -->
          <el-input
            v-if="field.type === 'input'"
            v-model="formData[field.prop]"
            :placeholder=" field.name"
            size="small"
            @change="handleChange"
            :clearable="field.clearable"
          />

          <!-- Select 类型 -->
          <el-select
            v-if="field.type === 'select'"
            v-model="formData[field.prop]"
            :placeholder=" field.name"
            size="small"
            @change="handleChange"
            :clearable="field.clearable"
          >
            <el-option
              v-for="option in field.formOptions"
              :key="option.val"
              :label="option.label"
              :value="option.val"
            />
          </el-select>

          <!-- MultiSelect 类型 -->
          <el-select
            v-if="field.type === 'multiSelect'"
            v-model="formData[field.prop]"
            :placeholder=" field.name"
            size="small"
            multiple
            @change="handleChange"
            :clearable="field.clearable"
          >
            <el-option
              v-for="option in field.formOptions"
              :key="option.val"
              :label="option.label"
              :value="option.val"
            />
          </el-select>

          <!-- DateRange 类型 -->
          <el-date-picker
            @change="handleChange"
            v-if="field.type === 'dateRange'"
            v-model="formData[field.prop]"
            type="daterange"
            range-separator="To"
            size="small"
            :clearable="field.clearable"
            start-placeholder="Start"
            end-placeholder="End"
            :shortcuts="shortcuts"
          />

          <!-- DateTimeRange 类型 -->
          <el-date-picker
            @change="handleChange"
            :clearable="field.clearable"
            v-if="field.type === 'datetimeRange'"
            v-model="formData[field.prop]"
            type="datetimerange"
            range-separator="To"
            size="small"
            start-placeholder="Start"
            end-placeholder="End"
            :shortcuts="shortcuts"
          />

          <!-- TreeSelect 类型 -->
          <el-tree-select
            @change="handleChange"
            :clearable="field.clearable"
            v-if="field.type === 'treeSelect'"
            v-model="formData[field.prop]"
            :data="field.treeFormOptions"
            :props="{
              value: field.ops?.primaryField || 'id',
              label: field.ops?.name || 'name',
              children: 'children'
            }"
            placeholder="pick"
            size="small"
          />

          <!-- Cascader 类型 -->
          <el-cascader
            @change="handleChange"
            :clearable="field.clearable"
            v-if="field.type === 'cascader'"
            v-model="formData[field.prop]"
            :options="field.cascaderOptions"
            :props="{
              value: field.ops?.valueField || 'id',
              label: field.ops?.labelField || 'name',
              emitPath: field.ops?.emitPath || false,
              checkStrictly: field.ops?.checkStrictly || false
            }"
            filterable
            :placeholder="field.name"
            size="small"
          >
            <template #default="{ node, data }">
              <span>{{ data[field.ops?.labelField || 'name'] }}</span>
              <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
            </template>
          </el-cascader>
        </div>
      </template>
    </div>

    <div class="searchbox-actions">
      <el-button
        v-if="hasMoreFields"
        size="small"
        type="default"
        @click="toggleCollapse"
      >
        {{ isCollapsed ? t('buttons.expand') : t('buttons.collect') }}
      </el-button>
      <el-button size="small" type="primary" @click="handleSearch">
        {{ t('sys.components.searchbox.search') }}
      </el-button>
      <el-button size="small" type="default" @click="handleReset">
        {{ t('sys.components.searchbox.reset') }}
      </el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, defineProps, defineEmits, watch, toRaw } from "vue";
import { ElInput, ElSelect, ElOption, ElDatePicker, ElTreeSelect } from 'element-plus';
import { getTimeRangeShortCut } from "@/utils/appCommon/timeUtil";
import { useI18n } from "vue-i18n";

const {t} = useI18n();

// 定义props类型
interface FieldBase {
  prop: string;
  name: string;
  type: 'input' | 'select' | 'multiSelect' | 'dateRange' | 'datetimeRange' | 'treeSelect' | 'cascader';
  showLabel?: boolean;
  default?: any; // 新增默认值
  clearable?: boolean; // 新增是否可清空
  valueType?: 'string' | 'number' | 'bool' ;
  isHidden?: boolean;  //是否隐藏  默认显示
}

interface InputField extends FieldBase {
  type: 'input';
}

interface SelectField extends FieldBase {
  type: 'select' | 'multiSelect';
  formOptions: Array<{ val: string | number; label: string }>;
}

interface DateRangeField extends FieldBase {
  type: 'dateRange' | 'datetimeRange';
}

interface TreeSelectField extends FieldBase {
  type: 'treeSelect';
  ops?: {
    primaryField?: string;
    parentField?: string;
    name?: string;
  };
  treeFormOptions: Array<Record<string, any>>;
}

interface CascaderField extends FieldBase {
  type: 'cascader';
  ops?: {
    valueField?: string;
    labelField?: string;
    emitPath?: boolean;
    checkStrictly?: boolean;
  };
  cascaderOptions: Array<Record<string, any>>;
}

type Field = InputField | SelectField | DateRangeField | TreeSelectField | CascaderField;

// 定义props
const props = defineProps<{
  fields: Field[];
  maxVisibleFields: number;
  initialValues?: Record<string, any>;
}>();

// 定义emits
const emit = defineEmits(['search', 'reset', 'change']);

// 响应式数据
const isCollapsed = ref(true);
// 修改formData初始化方式
const formData = reactive({ ...props.initialValues });

// 新增watch监听initialValues变化
watch(
  () => props.initialValues,
  (newVal) => {
    console.log(toRaw(newVal));
    Object.assign(formData, toRaw(newVal));
  },
  { deep: true, immediate: true }
);

// 添加刷新触发器
const refreshTrigger = ref(0);

// 提取展开/折叠方法
const toggleCollapse = () => {
  isCollapsed.value = !isCollapsed.value;
  // 强制刷新可见字段
  refreshTrigger.value++;
};

// 修改可见字段计算逻辑，依赖刷新触发器
const visibleFields = computed(() => {
  // 使用refreshTrigger确保每次切换都重新计算
  refreshTrigger.value;

  if (isCollapsed.value) {
    return props.fields.slice(0, props.maxVisibleFields);
  }
  // 展开时创建新数组引用
  return [...props.fields];
});

// 恢复hasMoreFields计算属性
const hasMoreFields = computed(() => props.fields.length > props.maxVisibleFields);

// 判断字段是否应该渲染
const shouldRenderField = (field: Field) => {
  return true;
};


// 处理搜索
const handleChange = () => {
  const rs =  { ...toRaw(formData) }
  emit('change', rs);
};

// 处理搜索
const handleSearch = () => {
  const rs =  { ...toRaw(formData) }
  emit('search', rs);
};


// 处理重置
const handleReset = () => {
  Object.keys(formData).forEach(key => {
    const field = props.fields.find(f => f.prop === key);
    formData[key] = field?.default !== undefined && field?.default !== null
      ? field.default
      : undefined;
  });
  emit('reset', {});
};

const shortcuts = ref(getTimeRangeShortCut())

</script>

<style scoped>
.searchbox-container {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  padding: 10px;
  background-color: #f5f5f5;
  border-radius: 4px;
}

.searchbox-fields {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  align-items: flex-start;
  max-height: none; /* 移除最大高度限制 */
  overflow-y: visible; /* 始终显示所有内容 */
}

/* 添加折叠状态样式 */
.searchbox-fields-collapsed {
  max-height: 200px; /* 折叠时限制高度 */
  overflow-y: auto; /* 折叠时显示滚动条 */
}

.searchbox-field {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.searchbox-label {
  font-size: 12px;
  color: #606266;
}

.searchbox-actions {
  display: flex;
  gap: 8px;
  align-items: center;
  margin-left: auto;
}

/* 紧凑型布局 */
.el-input, .el-select, .el-date-picker, .el-tree-select {
  width: 160px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .searchbox-container {
    flex-direction: column;
  }

  .searchbox-actions {
    margin-left: 0;
    justify-content: flex-start;
    width: 100%;
  }
}
</style>
